<?php
/**
 * 系统API接口类
 * @author           袁志蒙  
 * @license          http://www.yzmcms.com
 * @lastmodify       2017-01-18
 */

defined('IN_YZMPHP') or exit('Access Denied');
yzm_base::load_common('class/jst.class.php');
new_session_start();

class jst_timer{

	/**
	 方法：获取商品
	 定时器时间：30秒一次
	 */
	public function get_item(){
		$jst_list =get_jst_list();
		foreach($jst_list as $jst){
			$jst_id = $jst['id'];
			$jst = get_jst_list($jst_id);			
			$brand_list = get_brand_by_jst($jst_id);
			if(!$brand_list){
				continue;
			}
			//锁判断
			$lock = getcache('LOCK::get_item_'.$jst_id);
			if($lock!=0){
				echo $jst['short_name'].'商品数据获取中...'.PHP_EOL;
				continue;
			}
			setcache('LOCK::get_item_'.$jst_id,1,20);
			//读取记录缓存，计算开始时间结束时间
			$param['page_size'] = 10;
			$result = get_item_timer($jst_id,$param);
			if($result['status']==1){
				delcache('LOCK::get_item_'.$jst_id);
			}
			echo $result['msg'].PHP_EOL;
		}
	}
	
	//重新获取商品add_time=0的商品，删除无用商品使用
	public function reget_item(){
		$jst_list =get_jst_list();
		foreach($jst_list as $jst){
			$jst_id = $jst['id'];
			$jst = get_jst_list($jst_id);			
			$brand_list = get_brand_by_jst($jst_id);
			if(!$brand_list){
				continue;
			}
			//锁判断
			$lock = getcache('LOCK::reget_item_'.$jst_id);
			if($lock!=0&&0){
				echo $jst['short_name'].'重获商品数据获取中...'.PHP_EOL;
				continue;
			}
			setcache('LOCK::reget_item_'.$jst_id,1,20);
			$d = D('jst_sku');
			//后台配置获取多久前的商品
			if(!$day=get_config('last_sku_time')){
				$day=10;
			}
			$list = $d->field('i_id')->where(['add_time<'=>time()-$day*86400,'jst_id'=>$jst_id])->group('i_id')->order('add_time asc')->limit(20)->select();
			if(empty($list)){
				$result['msg'] = $jst['short_name'].'：已最新商品';
				delcache('LOCK::reget_item_'.$jst_id);
			}else{
				$param['i_ids']=array_column($list,'i_id');
				//读取记录缓存，计算开始时间结束时间
				$result = reget_item_timer($jst_id,$param);
				if($result['status']==1){
					delcache('LOCK::reget_item_'.$jst_id);
				}
			}
			echo $result['msg'].PHP_EOL;
		}
	}
	
	//每天重新获取当天更新产品，避免漏商品
	public function reget_item_today(){
		$d = D('jst_log');
		$time = strtotime(date('Y-m-d'))-86400;
		$res = $d->delete(['type'=>'item','modified_begin>'=>$time]);
		if($res!==false){
			echo '已重新获取时间'.date('Y-m-d H:i:s').'之后更新的商品资料';
		}else{
			echo '重新获取商品资料失败';
		}
	}
	
	//每天重新获取7天未更新的商品，不存在的商品删除-----弃用
	public function reget_item_7day(){
		return;
		$d_sku = D('jst_sku');
		$time = strtotime(date('Y-m-d'))-86400*7;
		$res = $d_sku->update(['add_time'=>0],['add_time>'=>$time]);
		if($res!==false){
			echo '已重新获取时间'.date('Y-m-d H:i:s').'之前的商品资料';
		}else{
			echo '重新获取商品资料失败';
		}
	}
	
	//每天重新获取7天未更新库存-----弃用
	public function reget_inventory_7day(){
		return;
		$d_sku = D('jst_sku');
		$time = strtotime(date('Y-m-d'))-86400*7;
		$res = $d_sku->update(['inventory_syn_time'=>0],['inventory_syn_time>'=>$time]);
		if($res!==false){
			echo '已重新获取时间'.date('Y-m-d H:i:s').'之前的商品库存';
		}else{
			echo '重新获取商品库存失败';
		}
	}
	
	//根据商品资料获取库存信息
	public function get_inventory(){
		//绑定库存聚水潭id列表
		$jst_list =get_brand_by_jst3();
		foreach($jst_list as $jst){
			$jst_id = $jst;
			$jst = get_jst_list($jst_id);			
			//锁判断
			$lock = getcache('LOCK::get_inventory_'.$jst_id);
			if($lock!=0&&0){
				echo $jst['short_name'].'商品库存获取中...'.PHP_EOL;
				continue;
			}
			setcache('LOCK::get_inventory_'.$jst_id,1,20);
			$d = D('jst_sku');
			if(!$day = get_config('last_inventory_time')){
				$day = 10;
			}
			$list = $d->field('sku_id')->where(['inventory_syn_time<'=>time()-86400*$day,'jst_id2'=>$jst_id])->order('inventory_syn_time asc')->limit(20)->select();
			if(empty($list)){
				$result['msg'] = '：已是最新库存';
				delcache('LOCK::get_inventory_'.$jst_id);
			}else{
				$param['sku_ids']=array_column($list,'sku_id');
				//读取记录缓存，计算开始时间结束时间
				$result = get_inventory_timer($jst_id,$param);
				if($result['status']==1){
					delcache('LOCK::get_inventory_'.$jst_id);
				}
			}
			echo $jst['short_name'].$result['msg'].PHP_EOL;
		}
	}
	
	/**
	 方法：订单
	 定时器时间：30秒一次
	 */
	public function get_orders(){		
		$shop_list =get_shop_all();
		$lock = getcache('LOCK::get_orders');
		if($lock!=0){
			echo '订单数据获取中...';
			exit;
		}
		setcache('LOCK::get_orders',1,20);
		$current_shop = [];
		foreach($shop_list as $shop){
			if(getcache('LOCK::get_orders_'.$shop['shop_id'])>0){
				continue;
			}
			//当前请求店铺
			$current_shop = $shop;
			break;
		}
		if(!$current_shop){
			exit('##全部店铺已是最新数据##');
		}
		//读取记录缓存，计算开始时间结束时间
		$param['page_size'] = 30;
		$param['shop_id'] = $current_shop['shop_id'];
		$result = get_orders_timer($current_shop['jst_id'],$param);
		if($result['status']==1){
			delcache('LOCK::get_orders');
		}
		if($result['status']==1&&strpos($result['msg'],'无数据')){
			setcache('LOCK::get_orders_'.$current_shop['shop_id'],1,$current_shop['order_freq']*5);
		}
		echo $result['msg'].$current_shop['nick'];
	}

	/*消息订阅-库存同步*/
	public function business_sku_syn(){
		$request = $_POST;
		if(!isset($_GET['jst_id'])){
			exit('{"code":"-1","msg":"jst_id不能为空"}');
		}
		$jst_id = $_GET['jst_id'];
		if(!isset($request['sign'])||!isset($request['timestamp'])||!isset($request['action_code'])){
			exit('{"code":"-1","msg":"参数错误"}');
		}
		$jst = get_jst_list($jst_id);
		$arr = [
			'app_key' => $jst['app_key'],
			'action_code' => $request['action_code'],
			'timestamp' => $request['timestamp'],
			'charset' => 'utf-8',
			'version' => 2,
			'biz' => $request['biz'],
		];
		$jst = new jst($jst_id);		
		$sign = $jst->sign($arr);
		//开放平台后台绑定，验证接口使用
		if($request['biz'] == '{}'){
			if($request['sign'] == $sign){
				exit('{"code":"0","msg":"验签成功"}');
			}else{
				exit('{"code":"-1","msg":"验签失败"}');
			}
		}
		
		if($sign != $request['sign']){
			exit('{"code":"-1","msg":"验签失败"}');
		}
		
		$request['biz'] = json_decode($request['biz'],true);
		$request['biz']['jst_id'] = $jst_id;
		//传递判断是否同步成功
		$res = redis_rpush('SYN::business_sku_syn',json_encode($request['biz']));
		if($res){
			exit('{"code":"0","msg":"执行成功"}');
		}else{
			exit('{"code":"-1","msg":"队列失败"}');
		}
	}
	
	/*消息订阅-写入数据库(削峰)*/
	public function business_sku_syn_insert($biz = ''){
		//读取条数
		$count = 200;
		$run_times = intval(getcache('LOCK::task_run_times'));
		//后台配置跑的速度
		if($run_times>=$count){
			delcache('LOCK::task_run_times');
			exit('处理'.$run_times.'条数据'.'，跑太快了，停一停！');
		}
		//返回队列并做备份
		$biz = redis_lpop('SYN::business_sku_syn');
		//没有数据
		if(!$biz){
			if(!$run_times){
				exit('没有数据需要跑！');
			}else{
				delcache('LOCK::task_run_times');
				exit('处理'.$run_times.'条数据');
			}
		}
		
		if($run_times){
			$run_times++;
		}else{
			$run_times = 1;
		}
		setcache('LOCK::task_run_times',$run_times);
		$biz = json_decode($biz,true);
		$info = [];
		foreach($biz as $k=>$v){//驼峰命名转下划线命名
			$key = uncamelize($k);
			$info[$key] = $v;
		}
		
		//吉普聚水潭根据保存codi判断
		if($info['coid']=='10054506'){
			$biz['jst_id'] =2;
		}
		//雅鹿聚水潭根据保存codi判断
		if($info['coid']=='10294537'){
			$biz['jst_id'] =3;
		}
		$msg = insert_inventory($info,$biz['jst_id']);
		
		//如果开启记录，插入数据库
		if(get_config('switch_inventory_syn')=='开启'){
			D('jst_inventorys_log')->insert([
				'sku_id'=>$info['sku_id'],
				'jst_id'=>$biz['jst_id'],
				'add_time'=>time(),
				'biz'=>'qty:'.$info['qty'].',in_qty:'.$info['in_qty'].',purchase_qty:'.$info['purchase_qty'].',virtual_qty:'.$info['virtual_qty'].',coid:'.$info['coid'],
				'status'=>$msg['code'],
				'msg'=>$msg['msg']
			]);
		}
		
		if($msg['code'] == 1){//同步库存成功，做记录
			$this->business_sku_syn_insert();
		}else{//操作失败重新加入队列
			redis_rpush('SYN::business_sku_syn',json_encode($biz));
		}
	}
	
	//删除无用记录
	public function delete_log(){
		/*删除取消订单数据*/
		//删除2天前的取消订单，近两天订单数据用于统计
		$time = strtotime(date('Y-m-d'))-2*86400;
		$res = D('jst_orders')->delete(['status_code'=>10,'order_date<'=>$time]);
		echo $res==false ? '删除取消订单数据成功||' : '删除取消订单数据失败||';
		//删除超过后台配置的天数前的订单
		$where = ['order_date<'=>time()-90*86400];
		$res = D('jst_orders')->delete($where);
		echo $res!==false ? '删除90前订单数据成功||' : '删除90前订单数据失败||';
		/*删除多余请求记录，保留近3天记录*/
		$res = D('jst_log')->delete(['add_time<'=>time()-3*86400]);
		echo $res!==false ? '删除3前聚水潭请求结果成功||' : '删除3前聚水潭请求结果失败||';
		//删除导出文件
		deleteDir(YZMPHP_PATH.'uploads/xlswriter' . '/');
	}
	
	//统计销量
	public function sales_by_sku($days='1days'){
		//先清空统计
		$days_arr = ['1days','2days','3days','5days','7days','30days'];
		//兼容管理后台操作
		if(!isset($_GET['days'])){
			//获取下个时间
			foreach($days_arr as $k=>$v){
				if($v == $days){
					$k++;
					break;
				}
			}
		}else{
			$days = $_GET['days']; 
		}
		//清空所有数据统计
		D('jst_sku_sales_'.$days)->delete([1=>1]);
		
		if(!$days||!in_array($days,$days_arr)){
			return;
		}
		//当天0点时间戳
		$end = strtotime(date('Y-m-d',time()));
		$start = $end - 86400*intval($days);
		$where = '1';
		//筛选时间范围内
		$where .= ' AND send_date>='.$start.' AND send_date<'.$end;
		//时间超过10点，不再统计异常订单，大多数是取消订单，仓库拆单导致统计不准，待优化
		/*
		if($days != '1days'){
			$where .= ' AND status_code in (2,7,8,9)';
		}else{
			//筛选发货中、异常、已付款待审核、已客审待财审、已发货的订单
			$where .= ' AND status_code in (2,4,7,8,9)';
		}*/
		$sql = 'insert into yzm_jst_sku_sales_'.$days.' (SELECT sku_id,sum( qty ) '.$days.',unix_timestamp(now()) sales_add_time FROM `yzm_jst_orders` WHERE '.$where.' group by sku_id)';
		//echo $sql;exit;
		$res = D('yzm_jst_sku_sales_'.$days)->query($sql);
		if($res){
			if(!isset($_GET['days'])){
				echo '成功统计'.intval($days).'天销量||';
				if(isset($days_arr[$k])){
					$this->sales_by_sku($days_arr[$k]);
				}else{
					exit('统计完成');
				}
			}else{
				return_json(array('status'=>1,'message'=>L('operation_success')));
			}
		}else{
			if(isset($_GET['days'])){
				return_json(array('status'=>0,'message'=>'统计失败'));
			}
			exit('统计'.intval($days).'天销量失败，'.date('Y-m-d H:i:s'));
		}
	}
	
	//订做采购单
	//一分钟一次
	public function get_purchase(){
		$jst_id = getcache('LOCK::get_purchase_jst_id');
		if($jst_id==1){
			$jst_id = 2;
		}else{
			$jst_id = 1;
		}
		setcache('LOCK::get_purchase_jst_id',$jst_id);
		//一分钟一次，没必要锁
		//if(getcache('LOCK::get_purchase')){
			//exit('##采购单信息已是最新数据##');
		//}
		//加锁，避免重复请求
		if(getcache('LOCK::get_purchase_run')){
			exit('采购单数据抓取中...');
		}
		//懒人锁1分钟
		setcache('LOCK::get_purchase_run',1,60);

		//查询该商品请求数据
		$log_info = D('jst_log')->where(['type'=>'purchaser','jst_id'=>$jst_id,'modified_begin>'=>0,'status'=>1])->order('id desc')->find();
		$day_time = 86400;
		
		$is_last_time = 0;
		if(isset($log_info['modified_begin'])){
			//如果不是最新数据（近30分钟），按天获取
			if($log_info['has_next']){
				$begin = $log_info['modified_begin'];
				$end = $log_info['modified_end'];
				$page_index = $log_info['page_index']+1;
			}else{
				$begin = $log_info['modified_end'];
				if(time()-$log_info['modified_end']>1800){
					$end = $begin+$day_time;//按天获取
				}else{
					$end = time();
					$is_last_time = 1;
				}
				$page_index = 1;
			}
		}else{
			//如果没有数据，使用开始使用聚水潭系统作为开始时间。按天获取
			$begin = strtotime(date('Y-m-d'))-get_config('last_purchase_time')*86400;
			$end = $begin+$day_time;
			$page_index = 1;
		}
		
		$jst = new jst($jst_id);
		$arr = [
			'modified_begin' => date('Y-m-d H:i:s',$begin),
			'modified_end' => date('Y-m-d H:i:s',$end),
			"page_index" => $page_index,
			"page_size" => 30
		];
		$result = $jst->purchase($arr);
		
		$jst_purchaser = D('jst_purchaser');
		$jst_purchaser_item = D('jst_purchaser_item');
		if($result['code'] == 0){
			$update_num = 0;
			$insert_num = 0;
			if($result['data']['datas']){
				foreach($result['data']['datas'] as $v){
					if($v['labels'] != '下单订做'){
						continue;
					}
					$insert_data = [];
					//插入采购单表
					$insert_data['po_id'] = $v['po_id'];
					$insert_data['seller'] = $v['seller'];
					$insert_data['purchaser_name'] = $v['purchaser_name'];
					$insert_data['receive_status'] = $v['receive_status'];
					$insert_data['remark'] = $v['remark'];
					$insert_data['status'] = $v['status'];
					$insert_data['supplier_id'] = $v['supplier_id'];
					$insert_data['confirm_date'] = $v['confirm_date']?strtotime($v['confirm_date']):0;
					$insert_data['finish_time'] = $v['finish_time']?strtotime($v['finish_time']):0;
					$insert_data['modified'] = strtotime($v['modified']);
					$insert_data['jst_id'] = $jst_id;
					//判断是否存在,存在就更新，不存在就插入
					$info = $jst_purchaser->where(['po_id'=>$v['po_id'],'jst_id'=>$jst_id])->find();
					if($info){
						$update_num++;
						$jst_purchaser->update($insert_data,['po_id'=>$v['po_id']]);
					}else{
						$insert_num++;
						$jst_purchaser->insert($insert_data);
					}

					
					//先删除，再插入采购单商品表
					$jst_purchaser_item->delete(['po_id'=>$v['po_id'],'jst_id'=>$jst_id]);
					$insert_item_data = [];
					//部分采购单没有商品的情况
					if(!$v['items']){
						continue;
					}
					//采购数量
					$qty = 0;
					foreach($v['items'] as $val){
						$item['sku_id'] = $val['sku_id'];
						$item['name'] = $val['name'];
						$item['price'] = $val['price'];
						$item['i_id'] = $val['i_id'];
						$item['po_id'] = $val['po_id'];
						$item['remark'] = $val['remark'];
						$item['qty'] = $val['qty'];
						$item['jst_id'] = $jst_id;
						$qty += $val['qty'];
						$insert_item_data[] = $item;
					}
					$jst_purchaser_item->insert_all($insert_item_data);
					//查询采购入库单，并更新实际入库
					$arr = [
						'po_ids' => [$v['po_id']],
						"page_index" => 1,
						"page_size" => 30
					];
					$purchasein_result = $jst->purchasein($arr);
					$act_qty = 0;
					if($purchasein_result['code'] == 0&&$purchasein_result['data']['datas']){
						foreach($purchasein_result['data']['datas'] as $purchasein){
							if($purchasein['items']){
								foreach($purchasein['items'] as $items){
									$act_qty += $items['qty'];
									$jst_purchaser_item->update(['act_qty'=>$items['qty']],['sku_id'=>$items['sku_id'],'po_id'=>$v['po_id']]);
								}
							}
						}
					}
					//更新实际入库数和采购数量
					$jst_purchaser->update(['act_qty'=>$act_qty,'qty'=>$qty],['po_id'=>$v['po_id'],'jst_id'=>$jst_id]);
				}
			}
			//判断是否更新到最新,锁5分钟，暂时没必要锁
			/*
			if($is_last_time&&!$result['data']['has_next']&&$result['data']['datas']){
				setcache('LOCK::get_purchase',1,300);
			}*/
			delcache('LOCK::get_purchase_run');
			
			//更新请求记录
			$jst = get_jst_list($jst_id);
			$msg = $jst['short_name'].'#'.date('Y-m-d H:i:s',$begin).'~'.date('Y-m-d H:i:s',$end).'第'.$page_index.'页,共更新'.$update_num.'条，共插入'.$insert_num.'条';
			$log_insert = ['type'=>'purchaser','modified_begin'=>$begin,'modified_end'=>$end,'add_time'=>time(),'has_next'=>$result['data']['has_next'],'page_index'=>$result['data']['page_index'],'msg'=>$msg,'status'=>1,'jst_id'=>$jst_id];
			D('jst_log')->insert($log_insert);
			echo $msg;
		}
	}
	
	//异常订单重新抓取，有些订单状态，貌似无法通过修改时间获取到。
	public function reget_orders(){
		if(getcache('LOCK::reget_orders_run')){
			//exit('数据相同不许更新！');
		}
		//分页获取
		$page = getcache('LOCK::reget_orders_page');
		$page = $page?$page:1;
		$where = '(status_code<7 and status_code <> 5 and status_code <> 3 and order_date<'.(time()-12*3600).') or (status_code=2 and order_from LIKE "%vip%") and add_time<'.(time()-12*3600);
		$total = D('jst_orders')->where($where)->total();
		if($page*50>$total){
			$next_page = 1;
		}else{
			$next_page = $page+1;
		}
		echo PHP_EOL . '获取第'.$page.'页，';
		$limit = ($page-1)*50;
		//超过24小时订单异常，重新获取

		$orders_list = D('jst_orders')->field('o_id,jst_id')->where($where)->order('order_date asc')->limit($limit.',50')->select();
		
		if($orders_list){
			$list = [];
			foreach($orders_list as $v){
				$list[$v['jst_id']][] = $v['o_id']; 
			}
			
			foreach($list as $k => $v){
				$jst_id = $k;
				$jst = new jst($jst_id);
				$result = $jst->orders(['o_ids'=>$v]);
				$msg = '';
				if($result['code']==0){
					//处理数据
					$result = $result['data'];
					if(isset($result['orders'])&&!empty($result['orders'])){
						$insert_data['has_next'] = $result['has_next'];
						$return = get_orders_data($jst_id,$result['orders']);
						$msg .= $return['msg'];
						$insert_data['status'] = $return['status'];
					}else{
						$insert_data['has_next'] = 0;
						$insert_data['status'] = 1;
						$msg .= '，无数据';
					}
				}else{
					$msg .= ',接口错误信息：'.$result['msg'];
					$insert_data['status'] = 0;		
				}
				echo $msg.PHP_EOL;
			}
			setcache('LOCK::reget_orders_page',$next_page);
		}else{
			echo '暂无异常订单处理';
		}
	}
	
	//商品品牌销量标签
	public function get_sku_tag_brand(){
		$brand = sku_tag_brand();
		foreach($brand as $v){
			$config = config_sku_tag($v);
			$case = '(CASE ';
			foreach($config as $k=>$c){
				if(isset($config[$k-1])){
					$case .= 'WHEN (ROUND(a.d,0)<'.$config[$k-1]['days_avg'].'&&ROUND(a.d,0)>='.$c['days_avg'].') THEN "'.$c['tag_name'].'" ';
				}else{
					$case .= 'WHEN (ROUND(a.d,0)>='.$c['days_avg'].') THEN "'.$c['tag_name'].'" ';
				}
			}
			$case .="END) tag";
			$sql = 'update yzm_jst_sku s,(select a.*,'.$case.' from (SELECT i_id,other_2,CONCAT(i_id,substring_index(properties_value,";",1)) kuan,sum(3days/3) 3d,sum(7days/7) 7d,if((sum(3days/3)-sum(7days/7))/sum(3days/3)>=0.1,sum(3days/3),sum(7days/7)) as d FROM `yzm_jst_sku_sales` where brand = "'.$v.'" group by CONCAT(i_id,substring_index( properties_value, ";",1)) order by 7days desc) a) b set s.labels_brand = b.tag where CONCAT(s.i_id,substring_index(s.properties_value,";",1)) = b.kuan and s.brand="'.$v.'"';
			$result = D('jst_sku_sales')->query($sql);
			//echo $sql;exit;
			if($result){
				echo '更新'.$v.'销量标签成功!||';
			}else{
				echo '更新'.$v.'销量标签失败!||';
			}
		}
	}	
	
	//计算头尾码
	public function get_touwei(){
		if(getcache('LOCK::get_touwei')){
			exit('已是更新完毕！');
		}
		if(getcache('LOCK::get_touwei_run')){
			exit('正在计算中！');
		}
		//懒人锁1分钟
		setcache('LOCK::get_touowei_run',1,60);
		$touwei = touwei();
		$number_chima = ['23'=>1,'24'=>2,'25'=>3,'26'=>4,'27'=>5,'28'=>6,'29'=>7,'30'=>8,'31'=>9,'32'=>10,'33'=>11,'34'=>12,'35'=>13,'36'=>14,'38'=>15,'40'=>16,'42'=>17];
		$letter_chima = ['XXS'=>1,'XS'=>2,'S'=>3,'M'=>4,'L'=>5,'XL'=>6,'XXL'=>7,'2XL'=>7,'XXXL'=>8,'3XL'=>8,'XXXXL'=>9,'4XL'=>9,'XXXXXL'=>10,'5XL'=>10,'XXXXXXL'=>11,'6XL'=>11];
		$i_id_list = D('jst_sku')->field('i_id')->where('tou_wei=0 and category<>"物料"')->order('id asc')->group('i_id')->limit(50)->select();
		if(!$i_id_list){
			delcache('LOCK::get_touwei_run');
			setcache('LOCK::get_touowei',1,3600);
			exit('更新完成！');
		}
		$sku_color_chima = [];
		foreach($i_id_list as $v){
			$sku_list = D('jst_sku')->field('sku_id,i_id,properties_value,sku_code')->where(['i_id'=>$v['i_id']])->select();
			//按颜色统计
			foreach($sku_list as $sku){
				if(strpos($sku['properties_value'],';')){
					$color = explode(';',$sku['properties_value'])[0];
				}else{
					D('jst_sku')->update(['tou_wei'=>-1],['i_id'=>$v['i_id']]);
					echo $v['i_id'].'规格格式错误';
					break;
				}
				if(strpos($sku['sku_code'],'-')){
					$str = explode('-',$sku['sku_code']);
					$chima =  end($str);
				}else{
					D('jst_sku')->update(['tou_wei'=>-1],['i_id'=>$v['i_id']]);
					echo $v['i_id'].'国标码格式错误!';
					break;
				}
			
				if(is_numeric($chima)){
					$sku_color_chima[$v['i_id']][$color][$chima] = $sku['sku_id'];
				}else{
					if(!isset($letter_chima[$chima])){
						D('jst_sku')->update(['tou_wei'=>-1],['i_id'=>$v['i_id']]);
						echo $v['i_id'].'尺码表不存在';
						break;
					}
					$sku_color_chima[$v['i_id']][$color][$letter_chima[$chima]] = $sku['sku_id'];
				}
			}
			delcache('LOCK::get_touwei_run');
		}
		
		//print_r($sku_color_chima);exit;
		foreach($sku_color_chima as $k=>$v){
			//颜色，先设置异常，
			D('jst_sku')->update(['tou_wei'=>-1],['i_id'=>$k]);
			foreach($v as $val){
				$count = count($val);
				//5个尺码以下，设置为均码
				$start = array_slice($touwei,0,1)[0];
				//print_r($start);
				if($count < $start['chima_num']){
					D('jst_sku')->update(['tou_wei'=>4],['i_id'=>$k]);
					echo '款式编码：'.$k.'--均码||';
					break;
				}
				//超多尺码
				if($count>end($touwei)['chima_num']){
					$this_touwei = end($touwei);
				}else{
					$this_touwei = $touwei[$count];
				}
				//排序
				ksort($val);
				//print_r($val);
				$i = 1;
				foreach($val as $sku_id){
					if($i<=$this_touwei['tou_num']){
						D('jst_sku')->update(['tou_wei'=>1],['sku_id'=>$sku_id]);
						echo '商品编码：'.$sku_id.'小码||';
					}elseif($i>$count-$this_touwei['wei_num']){
						D('jst_sku')->update(['tou_wei'=>3],['sku_id'=>$sku_id]);
						echo '商品编码：'.$sku_id.'大码||';
					}else{
						D('jst_sku')->update(['tou_wei'=>2],['sku_id'=>$sku_id]);
						//echo '商品编码：'.$sku_id.'中码||';
					}
					$i++;
				}
			}	
		}
		setcache('LOCK:get_touowei',1,60);
	}	

	//商品全局标签
	public function get_sku_tag_global(){
		//全局标签、多链接
		//$global = config_sku_tag('全局');
		//$sku_list = D('sku')->where('brand in ("增致牛仔 ZENGZHI","东方骆驼","雅鹿","法派FAPAI")')->group('brand,other_2')->select();
		//echo D('sku')->lastsql();exit;
		$type = isset($_GET['type']) ? $_GET['type'] : '';
		if(!$type){
			exit('参数错误！');
		}else if($type == 'new'){//新品标签
			$time = time()-40*86400;
			D('jst_sku')->update('labels=""','1');
			$result = D('jst_sku')->update('labels=CONCAT(labels,if(labels<>"",",新品","新品"))','created>'.$time);
			$tag_name = '新品标签';
		}else if($type == 'multilink'){//多链接
			$sql = 'update yzm_jst_sku s left join (SELECT other_2,brand,count(1) count FROM yzm_jst_sku WHERE enabled=1 and brand in ("增致牛仔 ZENGZHI","东方骆驼","雅鹿","法派FAPAI","安瑞井","美丽衣橱","GOOGIMS","ICE","JEEP","衣品天成","虎都") GROUP BY brand,other_2 having count>1) a on a.brand=s.brand and s.other_2=a.other_2 set labels = "多链接" where a.count>1';
			$result = D('jst_sku')->query($sql);
			$tag_name = '多链接标签';
		}else if($type == 'beihuo_fapai'){//法派备货仓
			//法派，进货仓有库存既是备货仓
			$sql = 'update yzm_jst_sku s left join (SELECT other_2 FROM yzm_jst_inventorys WHERE `brand` = "法派FAPAI" AND in_qty > 0 group by other_2) i on s.other_2 = i.other_2  set labels = CONCAT(labels,if(labels<>"",",备货仓","备货仓")) where s.brand="法派FAPAI"';
			$result = D('jst_sku')->query($sql);
			$tag_name = '法派备货仓标签';
		}else if($type == 'beihuo_yousheng'){//佑晟备货仓
			//佑晟，共享仓仓有库存既是备货仓
			$sql = 'update yzm_jst_sku s left join yzm_jst_inventorys i on s.other_2 = i.other_2 set labels = CONCAT(labels,if(labels<>"",",备货仓","备货仓")) where s.brand in ("增致牛仔 ZENGZHI","东方骆驼","雅鹿","安瑞井","米菲 MIFFY","美丽衣橱","ICE","衣品天成","虎都") and i.brand = "佑晟共享仓" and i.qty>0 and s.other_2<>""';
			$result = D('jst_sku')->query($sql);
			$tag_name = '佑晟备货仓标签';
		}else if($type == 'beihuo_jeep'){//JEEP备货仓
			//JEEP半成品有库存既是备货仓
			$sql = 'update yzm_jst_sku s left join yzm_jst_inventorys i on s.other_2 = i.other_2 set labels = CONCAT(labels,if(labels<>"",",备货仓","备货仓")) where s.brand ="JEEP" and i.brand = "JEEP半成品" and i.qty>0 and s.other_2<>""';
			$result = D('jst_sku')->query($sql);
			$tag_name = 'JEEP备货仓标签';
		}
		if(isset($_GET['ajax'])){
			if($result){
				return_json(array('status'=>1,'message'=>'更新'.$tag_name.'成功!'));
			}else{
				return_json(array('status'=>0,'message'=>'更新'.$tag_name.'失败!'));
			}
		}else{
			if($result){
				exit('更新'.$tag_name.'成功!');
			}else{
				exit('更新'.$tag_name.'失败!');
			}
		}

	}

	//测试
	public function test(){
		
        $config = ['path' => YZMPHP_PATH.'uploads/xlswriter' . '/'];
		$excel = new \Vtiful\Kernel\Excel($config);
$excel  = new \Vtiful\Kernel\Excel($config);
		for($i=1;$i<1000;$i++){
			$data_temp['A'] = '这是A'.$i;
			$data_temp['B'] = '这是B'.$i;
			$data_temp['C'] = '这是A'.$i;
			$data_temp['D'] = '这是B'.$i;
			$data_temp['E'] = '这是A'.$i;
			$data_temp['F'] = '这是B'.$i;
			$data_temp['G'] = '这是A'.$i;
			$data_temp['H'] = '这是B'.$i;
			$data_temp['I'] = '这是A'.$i;
			$data_temp['J'] = '这是B'.$i;
			$data[] = $data_temp;
		}
// fileName 会自动创建一个工作表，你可以自定义该工作表名称，工作表名称为可选参数
$filePath = $excel->fileName('tutorial01.xlsx', 'sheet1')
    ->header(['Item', 'Cost'])
    ->data([
        ['Rent', 1000],
        ['Gas',  100],
        ['Food', 300],
        ['Gym',  50],
    ])
    ->output();
		$excel->close();
		echo $filePath;exit;
		
		

//删除文件
deleteDir(YZMPHP_PATH.'uploads/xlswriter' . '/');
		
//测试获取品牌库存绑定聚水潭		
print_r(get_brand_by_jst3());exit;
		
		
		
		
		//测试xsl
$config = ['path' => YZMPHP_PATH.'uploads/xlswriter' . '/'];
$excel = new \Vtiful\Kernel\Excel($config);

// 此处会自动创建一个工作表
$fileObject = $excel->fileName("tutorial01.xlsx");

$fileObject->header(['name', 'age'])
    ->data([['viest', 21]]);

// 向文件中追加一个工作表
$fileObject->addSheet()
    ->header(['12312312', 'age'])
    ->data([['wjx', 22]]);

// 最后的最后，输出文件
$filePath = $fileObject->output();
		return;
		
		
		//误删除jst_log订单抓取记录
		$insert = [];
		$insert['type'] = 'orders';
		$insert['modified_begin'] = strtotime(date('Y-m-d'));
		$insert['modified_end'] = strtotime(date('Y-m-d'));
		$insert['status'] = 1;
		$insert['msg'] = '系统插入';
		$insert['add_time'] = time();
		foreach(get_shop_all() as $v){
			$insert['shop_id'] = $v['shop_id'];
			$insert['jst_id'] = $v['jst_id'];
			$res = D('jst_log')->insert($insert);
		}
		return;
		
		//测试库存插入数据库问题
		$biz = '{"customizeQty2":0,"customizeQty1":0,"iId":"YC466JK420","pickLock":0,"returnQty":3,"coid":12108573,"purchaseQty":0,"inQty":0,"defectiveQty":0,"qty":0,"name":"\u5973\u5f0f\u725b\u4ed4\u88e4\uff08\u6c34\u6d17\u4ea7\u54c1\uff09","modified":"2024-06-24 11:19:09.853","customizeQty7":0,"orderLock":0,"maxQty":0,"customizeQty5":0,"skuId":"YC466JK42003A","customizeQty4":0,"virtualQty":0,"jst_id":"5"}';
		$biz = json_decode($biz,true);
		$info = [];
		foreach($biz as $k=>$v){//驼峰命名转下划线命名
			$key = uncamelize($k);
			$info[$key] = $v;
		}
		$msg = insert_inventory($info,$biz['jst_id']);
		var_dump($msg);exit;
	}
} 